package com.example.demo.Configure;

import com.example.demo.Annoation.MyHandlerAnnotation;
import com.example.demo.Context.MyContext;
import com.example.demo.Service.MyHandler;
import org.cent.scanner.core.scanner.ClassScanner;
import org.cent.scanner.core.scanner.impl.DefaultClassScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class HandlerProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String,Class> map=new HashMap<>();
        ClassScanner classScanner=new DefaultClassScanner();
        classScanner.scanByAnno(Arrays.asList("com.example.demo.Service"), MyHandlerAnnotation.class).forEach(
                aClass -> {
                    String value=((MyHandlerAnnotation)aClass.getAnnotation(MyHandlerAnnotation.class)).value();
                    map.put(value,aClass);
                }
        );
        MyContext myContext=new MyContext(map);
        configurableListableBeanFactory.registerSingleton(myContext.getClass().getName(),myContext);
    }
}
